<template>
  <LoginFormTitle v-show="getShow" class="enter-x" />
  <Form class="p-4 enter-x" :model="formData" :rules="getFormRules" ref="formRef" v-show="getShow" @keypress.enter="handleLogin">
    <FormItem name="account" class="enter-x">
      <Input size="large" v-model:value="formData.account" :placeholder="t('sys.login.userName')" class="fix-auto-fill" />
    </FormItem>
    <FormItem name="password" class="enter-x">
      <InputPassword size="large" visibilityToggle v-model:value="formData.password" :placeholder="t('sys.login.password')" />
    </FormItem>

    <!--验证码-->
    <ARow class="enter-x">
      <ACol :span="12">
        <FormItem name="captchaValue" class="enter-x">
          <Input size="large" v-model:value="formData.captchaValue" :placeholder="t('sys.login.inputCode')" style="min-width: 100px" />
        </FormItem>
      </ACol>
      <ACol :span="8">
        <FormItem :style="{ 'text-align': 'right', 'margin-left': '20px' }" class="enter-x">
          <img
            v-if="randCodeData.requestCodeSuccess"
            style="margin-top: 2px; max-width: initial"
            :src="randCodeData.originalImageBase64"
            @click="handleChangeCheckCode"
          />
          <img v-else style="margin-top: 2px; max-width: initial" src="../../../assets/images/checkcode.png" @click="handleChangeCheckCode" />
        </FormItem>
      </ACol>
    </ARow>

    <ARow class="enter-x">
      <ACol :span="12">
        <FormItem>
          <!-- No logic, you need to deal with it yourself -->
          <Checkbox v-model:checked="rememberMe" size="small">
            {{ t('sys.login.rememberMe') }}
          </Checkbox>
        </FormItem>
      </ACol>
      <ACol :span="12">
        <FormItem :style="{ 'text-align': 'right' }">
          <!-- No logic, you need to deal with it yourself -->
          <Button type="link" size="small" @click="setLoginState(LoginStateEnum.RESET_PASSWORD)">
            {{ t('sys.login.forgetPassword') }}
          </Button>
        </FormItem>
      </ACol>
    </ARow>

    <FormItem class="enter-x">
      <Button type="primary" size="large" block @click="handleLogin" :loading="loading">
        {{ t('sys.login.loginButton') }}
      </Button>
      <!-- <Button size="large" class="mt-4 enter-x" block @click="handleRegister">
              {{ t('sys.login.registerButton') }}
            </Button> -->
    </FormItem>

    <ARow v-if="getHasQrCodeLogin" class="enter-x">
      <ACol :md="8" :xs="24" >
        <Button block @click="setLoginState(LoginStateEnum.MOBILE)">
          {{ t('sys.login.mobileSignInFormTitle') }}
        </Button>
      </ACol>
      <ACol  :md="8" :xs="24" class="!my-2 !md:my-0 xs:mx-0 md:mx-2">
        <Button block @click="setLoginState(LoginStateEnum.QR_CODE)">
          {{ t('sys.login.qrSignInFormTitle') }}
        </Button>
      </ACol>
      <ACol :md="7" :xs="24">
        <Button block @click="setLoginState(LoginStateEnum.REGISTER)">
          {{ t('sys.login.registerButton') }}
        </Button>
      </ACol>
    </ARow>

    <ARow v-else class="enter-x">
      <ACol :md="11" :xs="24" class="md:mr-2">
        <Button block @click="setLoginState(LoginStateEnum.MOBILE)">
          {{ t('sys.login.mobileSignInFormTitle') }}
        </Button>
      </ACol>
      <ACol :md="12" :xs="24" class="md:ml-2 !my-2 !md:my-0">
        <Button block @click="setLoginState(LoginStateEnum.REGISTER)">
          {{ t('sys.login.registerButton') }}
        </Button>
      </ACol>
    </ARow>

    <Divider v-if="getPlatformConfig().ldpConnectList?.length > 0" class="enter-x">{{ t('sys.login.otherSignIn') }}</Divider>
    <div class="flex justify-evenly enter-x" :class="`${prefixCls}-sign-in-way`">
      <template v-for="item in (getPlatformConfig().ldpConnectList as any[])">
        <!-- gitee授权登录 -->
        <Tooltip 
          placement="top" 
          v-if="item.grantType === GrantTypeEnum.GITEE" 
          @click="onThirdAuthRender(`${item.grantType}`)" 
          :title="item.displayName"
        >
          <GithubFilled />
        </Tooltip>

        <!-- 微信网页授权 -->
        <Tooltip 
          placement="top" 
          v-if="item.grantType === GrantTypeEnum.WX_H5" 
          @click="onThirdAuthRender(`${item.grantType}`)" 
          :title="item.displayName"
        >
          <WechatFilled />
        </Tooltip>

        <!-- 钉钉h5微应用 -->
        <Tooltip 
          placement="top" 
          v-if="item.grantType === GrantTypeEnum.DINGTALK" 
          @click="onThirdAuthRender(`${item.grantType}`)" 
          :title="item.displayName"
        >
          <DingtalkCircleFilled />
        </Tooltip>
        

        <!-- 企业微信 -->
        <Tooltip 
          placement="top" 
          v-if="item.grantType === GrantTypeEnum.WX_QY" 
          @click="onThirdAuthRender(`${item.grantType}`)" 
          :title="item.displayName"
        >
          <icon-font class="item-icon" type="icon-qiyeweixin3" />
        </Tooltip>
      </template>
      
    </div>
  </Form>

  <LoginSelect ref="loginSelectRef" />
</template>
<script lang="ts" setup>
  import { reactive, ref, toRaw, unref, computed, onMounted } from 'vue';
  import { Checkbox, Form, Input, Row, Col, Button, Divider, Tooltip } from 'ant-design-vue';
  import { 
    GithubFilled, 
    WechatFilled, 
    DingtalkCircleFilled, 
    createFromIconfontCN,
  } from '@ant-design/icons-vue';
  import LoginFormTitle from './LoginFormTitle.vue';
  import LoginSelect from './LoginSelect.vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { PageEnum } from '/@/enums/pageEnum'

  import { useUserStore } from '/@/store/modules/user';
  import { 
    LoginStateEnum, GrantTypeEnum, useLoginState, 
    useFormRules, useFormValid, qrCodeGrantTypes
  } from './useLogin';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { getImageCaptcha, getUserInfo } from '/@/api/auth';
  import { getPlatformConfig } from '/@/utils/cache/module'
  import { useGitUser } from './useGitUser';
  import { useRouter, useRoute } from "vue-router"
  import { thirdAuthRender } from '/@/api/auth'
  import { openWindow } from '/@/utils'

  // 本地登录或者三方登录成功之后返回的页面
  const router = useRouter()
  const route = useRoute()
  const redirect = router.currentRoute.value.query?.redirect as string
  const gitUserId = router.currentRoute.value.query?.gitUserId
  const ACol = Col;
  const ARow = Row;
  const FormItem = Form.Item;
  const InputPassword = Input.Password;
  const IconFont = createFromIconfontCN({
    scriptUrl: '//at.alicdn.com/t/font_2316098_umqusozousr.js',
  });
  const { t } = useI18n();
  const { notification, createMessage } = useMessage();
  const { prefixCls } = useDesign('login');
  const userStore = useUserStore();

  const { setLoginState, getLoginState } = useLoginState();
  const { getFormRules } = useFormRules();

  const formRef = ref();
  const loading = ref(false);
  const rememberMe = ref(false);
  const accessToken = ref<any>('')

  const formData = reactive({
    account: 'yanshi',
    password: '123456',
    captchaValue: '',
  });
  const randCodeData = reactive({
    originalImageBase64: '',
    requestCodeSuccess: false,
    token: null,
  });

  const { validForm } = useFormValid(formRef);

  //onKeyStroke('Enter', handleLogin);
  const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN);
  // 获取有扫码登录的方式
  const getHasQrCodeLogin = computed(() => {
    // @ts-ignore
    return getPlatformConfig()?.ldpConnectList?.filter(e=> qrCodeGrantTypes.includes(e.grantType)).length > 0
  });

  /**
   * 首页多租户部门弹窗逻辑
   */
  const loginSelectRef = ref();

  async function handleLogin() {
    // 判断用户是否star
    await useGitUser(gitUserId).confirmStar()

    const data = await validForm();
    if (!data) return;
    try {
      loading.value = true;
      await userStore.login(
        toRaw({
          password: data.password,
          account: data.account,
          captchaValue: data.captchaValue,
          captchaType: 'image',
          captchaToken: randCodeData.token,
          mode: 'none', //不要默认的错误提示
        })
      );

      // 如果是租户成员邀请, 直接跳转
      if (redirect?.startsWith(PageEnum.INVITE_USER_JOIN_TENANT)) {
        openWindow(redirect, { target: '_self' });
        return
      }

      loginSelectRef.value.show();
    } catch (error) {
      notification.error({
        message: t('sys.api.errorTip'),
        description: error.message || t('sys.api.networkExceptionMsg'),
        duration: 3,
      });
      loading.value = false;

      //登录页面，当输入验证码错误时，验证码图片要刷新一下，而不是保持旧的验证码图片不变
      handleChangeCheckCode();
    } finally {
      loading.value = false
    }
  }
  function handleChangeCheckCode() {
    formData.captchaValue = '';
    //TODO 兼容mock和接口，暂时这样处理
    getImageCaptcha().then(res=>{
      randCodeData.originalImageBase64 = res.originalImageBase64
      randCodeData.requestCodeSuccess = true
      randCodeData.token = res.token
    });
  }

  /**
   * 第三方登录
   * @param type
   */
  async function onThirdAuthRender(grantType) {
    const data = await thirdAuthRender({ grantType, backUrl: redirect })
    window.location.href = data.pageUrl
  }

  //初始化验证码
  onMounted(() => {
    handleChangeCheckCode();
  });
</script>
<style>
  .gp {
    padding-bottom: 15px;
    font-size: 16px;
  }
  .gp,
  .gp a {
    color: #d21919;
  }
</style>
